﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BizzCommInterfaces;
using System.ServiceModel;
using WCFTrays.WCFServer;

namespace WCFTrays
{
    public class WCFOutbox : Tray, IOutbox
    {
        private const char _separator = '|';
        public string connString { get; set; }
        public string hostUrl { get; set; }
        public string selectMessageQuery { get; set; }
        private BasicHttpBinding binding;
        EndpointAddress addr;

        public WCFOutbox()
            :base()
        {
            base._name = "WCFOutboxProvider";
            binding = new BasicHttpBinding();
            hostUrl = "http://";
            connString = "Server=SERVIDOR;Database=BASEDEDATOS;Integrated Security=True";
        }

        #region IOutbox Members

        public string codeMe()
        {
            string ret = connString + _separator + hostUrl + _separator + _concreteName + _separator + selectMessageQuery;
            return ret;
        }

        public void decodeMe(string box)
        {
            string[] attr = box.Split(_separator);
            connString = attr[0];
            hostUrl = attr[1];
            _concreteName = attr[2];
            selectMessageQuery = attr[3];
            try
            {
                addr = new EndpointAddress(hostUrl);
            }
            catch
            {

            }
        }

        public string getConcreteOutboxName()
        {
            return _concreteName;
        }

        public void getConfigurationWindow()
        {
            WCFOutboxConfigControl configWindow = new WCFOutboxConfigControl(this);
            configWindow.ShowDialog();
            try
            {
                addr = new EndpointAddress(hostUrl);
            }
            catch
            {
                //Esto es por si el usuario ingresa una url invalida.
                //En esta ocación no se controla que la misma este bien formada
                //pero se evita que se caiga el sistema y/o que quede inconsistente
            }
        }

        public int getCount()
        {
            int count = 0;
            using (ServerManagerClient server = new ServerManagerClient(binding, addr))
            {
                count = server.getMessages(selectMessageQuery, null,connString).Count();
            }
            return count;
        }

        public string[] getDescription()
        {
            string[] ret = new string[4];
            ret[0] = "Cada mensaje será escrito a través de un servidor WCF.";
            ret[1] = "";
            ret[2] = "Se debe configurar la consulta para obtener los mensajes, ejemplo: SELECT * FROM Mensajes.";
            ret[3] = "";
            return ret;
        }

        public string getOutboxName()
        {
            return _name;
        }

        public bool isReady()
        {
            return (connString != null && selectMessageQuery != null && hostUrl != null && _concreteName != null);
        }

        public void setConcreteOutboxName(string name)
        {
            _concreteName = name;
        }

        public void writeMessage(BizzMessage msg)
        {
            try
            {
                using (ServerManagerClient server = new ServerManagerClient(binding, addr))
                {
                    server.writeNewMessageToDb(convertBizzMessageToWcfMessage(msg), connString);
                }
            }
            catch (Exception ex)
            {

            }

        }

        private WcfMessage convertBizzMessageToWcfMessage(BizzMessage msg)
        {
            WcfMessage retMsg = new WcfMessage();
            retMsg.Titulo = msg.Title;
            retMsg.Procesado = false;
            List<WcfMsgAttribute> attribList = new List<WcfMsgAttribute>();
            foreach (MsgAttribute m in msg.Attributes)
            {
                attribList.Add(new WcfMsgAttribute()
                {
                    AttrName = m.Name,
                    AttrType = m.Type.ToString(),
                    AttrValue = m.Value
                });
            }
            retMsg.AttributeList = attribList.ToArray();
            return retMsg;
        }

        #endregion
    }
}
